<style scoped>
.group_row{flex-wrap: wrap;margin-bottom: 5px;}
.group_title{width: 180px;padding-right: 5px;margin-right: 5px;border-right: 1px solid var(--sm_bg);}
.group_item_input{width: 80px;}
.group_row .group_item{margin-right: 10px;}
.add_from_submit{justify-content: flex-end;}
</style>
<template>
  <div class="form_item-sku">
    <input type="hidden" :name="name" :value="value">
    <el-dialog v-model="add_from.show" title="新规格组" draggable >
      <forms ref="forms" :config="add_from.config" @submit:forms="group_add"> </forms>
    </el-dialog>
    <div v-for="(row,i) in group" class="group_row flex">
      <div class="group_title flex">
        <el-input class="max" :disabled="!!is_info" @change="group_change_after()" v-model="row.title"/>
        <div style="width: 5px;"></div>
        <template v-if="!is_info">
          <el-button v-if="i>0" @click="group_del(i)" type="danger">删除组</el-button>
          <el-button v-else @click="add_from.show=true" type="primary">添加组</el-button>
        </template>
      </div>
      <el-tag v-for="(v,i2) in row.children" class="group_item" :closable="row.children.length>0" type="primary" @close="group_item_del(row,i2)">{{v}}</el-tag>
      <template v-if="!is_info">
        <el-input v-if="row.add_value!==false" v-model="row.add_value" class="group_item_input" size="small" @keyup.enter="group_item_add(row)" @blur="group_item_add(row)" />
        <el-button v-else class="button-new-tag" size="small" @click="row.add_value=''">添加选项</el-button>
      </template>
    </div>
    <list :cols="cols" :data="this_value"></list>
  </div>
</template>

<script>
// config 格式：{ban_price_vip:隐藏会员价, ban_stock:隐藏库存}
import s94Mjs from "s94-js";
import {ajax} from "@/js/api_tool.js";

export default {
  _title_: '规格',
  _can_form_param_: true,
  name: "sku",
  props: ['name', 'value', 'config', 'is_info', 'size', 'is_list'],
  emits: ['update:value', 'change'],
  data(){
    return {
      need_display: true,
      this_value: [],

      add_from: {
        show: false,
        config: {
          title: {label:'组标题',name:'title',type:'text_one',config:'',value:'',tips:'规格组标题', validate:["required"]},
          children: {label:'规格选项',name:'children',type:'select_more',config:[],tips:'选择预定的规格选项',value:''},
        },
      },
      old_sku_arr: [],
      group: [{title:'规格', add_value:false, children:['默认']}],
      sku_group_config: [],
      def_cols: {
        title: {name:'title', label:'规格标题', type:'text_one'},
        // link_id: {name:'link_id', label:'关联数据ID', width: '80px'},
        price: {name:'price', label:'价格', type:'text_one',config:'number', width: '120px', onchange:this.sku_change},
        price_vip: {name:'price_vip', label:'会员价', type:'hidden',config:'number', width:'120px', onchange:this.sku_change},
        stock: {name:'stock', label:'库存', type:'hidden',config:'number', width: '120px', onchange:this.sku_change},
        default: {name:'default', label:'默认', type:'radio_switch',config:'', width: '120px', onchange:this.sku_change},
        // action: {name:'action', label:'操作', type:'action',config:'number', width: '60px'},
      },
      cols: [],
    }
  },
  methods: {
    update_value(v){
      this.need_display = false;
      setTimeout(()=>{this.need_display = true;},5);
      this.$emit('update:value', v);
      this.$emit('change', v);
    },
    group_add(){
      let title = this.add_from.config.title.value;
      let children = this.add_from.config.children.value;
      children = children ? children.split(',') : [];
      children = Array.from(new Set(children));
      this.group.push({title:title, add_value:false, children:children});
      this.add_from.show = false;
      this.$refs.forms.init();
      this.group_change_after();
    },
    group_del(i){
      this.confirm(`是否确定删除【${this.group[i].title}】组及其全部选项`, ()=>{
        this.group.splice(i, 1);
        this.group_change_after();
      })
    },
    group_item_add(row){
      let val = row.add_value;
      row.add_value = false;
      if (~row.children.indexOf(val)) return this.tips(`选项【${val}】重复`);
      if (val) {
        row.children.push(val);
        this.group_change_after();
      }
    },
    group_item_del(row,i){
      // if (row.children.length <= 1) return this.tips(`选项数量不能小于1`);
      row.children.splice(i, 1);
      this.group_change_after();
    },
    group_change_after(){
      let group_config = {};
      let sku_config = {};
      let sku_list = [{title:[], group_key:[], sku_index:0}];
      let base = 1;
      this.group.forEach((row,i)=>{
        if (row.children.length <= 0) return;
        let g = row.title;
        let old_list = sku_list;
        sku_list = [];
        group_config[g] = [];
        sku_config[g] = {};
        old_list.forEach(function (old){
          row.children.forEach((v,i2)=>{
            let index = i2*base;
            group_config[g].push(v);
            sku_config[g][v] = index;
            sku_list.push({
              title: old.title.concat([g+':'+v]),
              group_key: old.group_key.concat([i2]),
              sku_index: old.sku_index + index,
            })
          })
        })
        base *= row.children.length;
      })
      let old_sku_arr = this.this_value || [];
      let has_default = false;
      this.this_value = [];
      sku_list.forEach((v,i)=>{
        if (v.title.length <= 0) return;
        let row = old_sku_arr[i] || this.old_sku_arr[i] || {price: '', price_vip: '', stock: 100, default:0};
        row.title = v.title.join(' ,');
        row.group_key = v.group_key.join('_');
        row.group_config = JSON.stringify(group_config);

        row.sku_index = v.sku_index;
        row.sku_config = JSON.stringify(sku_config);
        if (has_default){
          row.default = 0;
        }else if(row.default == 1){
          has_default = true;
        }
        this.this_value.push(row);
      });
    },
    display_value(){
      let sku_arr = [];
      let value = this.value;
      if (value && typeof value === 'string'){
        sku_arr = Object.values(JSON.parse(value));
      }else if (typeof value === 'object'){
        sku_arr = Object.values(value);
      }
      this.this_value = sku_arr;
      this.old_sku_arr = sku_arr.map(row=>{return row;});
      this.group = [];
      let sku_config = {};
      if (sku_arr.length){
        try {
          sku_config = JSON.parse(sku_arr[0].sku_config);
          Object.keys(sku_config).forEach(g => {
            let option_map = sku_config[g];
            let group_row = {title: g, add_value: false, children: []};
            Object.keys(option_map).forEach(k => {
              group_row.children.push(k);
            })
            group_row.children = Array.from(new Set(group_row.children));
            this.group.push(group_row);
          })
        } catch (e) {}
      }
      if (!this.group.length){
        this.group = [{title:'规格', add_value:false, children:['默认']}];
      }
      this.group_change_after();
      return sku_arr;
    },
    encode_value(){
      return JSON.stringify(this.this_value);
    },
    sku_change(row, col, v){
      if (col.name=='default'){
        this.this_value.forEach((row)=>{ row.default = 0; }) //清理默认
      }
      row[col.name] = v;
    },
    display_config(){
      let config = this.config;
      try {
        if (typeof config === 'string') config = JSON.parse(config);
      } catch (e) {}
      config = typeof config==='object' ? config : {};
      let can_edit = !this.is_info;

      this.cols = Object.values(this.def_cols).map(row=>{
        if (row.name !== 'title') row.can_edit = can_edit;
        if (row.name === 'price_vip'){
          row.type = config.ban_price_vip ? 'hidden':'text_one';
        }
        if (row.name === 'stock'){
          row.type = config.ban_stock ? 'hidden':'text_one';
        }
        return row;
      })
    },
  },
  watch: {
    value(){
      if (!this.need_display) return;
      this.display_value();
    },
    this_value: {
      handler() {
        this.need_display = false;
        setTimeout(()=>{this.need_display = true;},5);
        let v = this.encode_value();
        this.$emit('update:value', v);
        this.$emit('change', v);
      },
      deep: true
    },
    config(){
      this.display_config();
    },
    is_info(){
      this.display_config();
    },
  },
  computed: {
  },
  mounted() {
    this.display_value();
    this.display_config();

    ajax({url:'/admin/sku_group/list',cache:true}, (res)=>{
      let config = [];
      s94Mjs.each(res.data.list, function (row, i){
        config.push({
          content: row.title,
          value: '',
          children: row.option.split(',').map(v=>{return {content:v, value:v}; }),
        })
      })
      this.add_from.config.children.config = config;
      return false
    })
  }
}
</script>